package com.qc.controller;

import java.io.BufferedOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.qc.common.CollectionUtil;
import com.qc.common.Constants;
import com.qc.common.DateUtil;
import com.qc.common.SMSClient;
import com.qc.common.Session;
import com.qc.common.StringUtil;
import com.qc.common.Util;
import com.qc.common.XmlUtil;
import com.qc.entity.OrderAlipayCallBackEntity;
import com.qc.entity.OrderBillEntity;
import com.qc.entity.OrderCommentEntity;
import com.qc.entity.OrderEntity;
import com.qc.entity.OrderScheduleEntity;
import com.qc.entity.OrderWXpayCallBackEntity;
import com.qc.entity.SkillTagEntity;
import com.qc.entity.SystemMessageEntity;
import com.qc.entity.UserEntity;
import com.qc.entity.WXPayEntity;
import com.qc.entity.info.MyOrderInfo;
import com.qc.pay.AlipayUtil;
import com.qc.pay.WXPayUtil;
import com.qc.serverlistener.CacheUtil;
import com.qc.service.OrderService;
import com.qc.service.SystemMessageService;

import net.sf.json.JSONObject;

@Controller
public class OrderController extends BaseController {

	@Resource
	private OrderService orderService;
	
	@Resource(name="systemMessageService")
	private SystemMessageService systemMessageService;
	
	@RequestMapping(value = "/MobileAddOrder", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileAddOrder(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderEntity entity = (OrderEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderEntity.class); 
		
		List<OrderEntity> orderEntities = orderService.getSecretaryBySecUserId(entity.getSecretaryUserId());
		for (OrderEntity orderEntity : orderEntities) {
			//已经存在的订单的结束时间 与 当前订单的开始时间 相比，如果小于就正常
			long endStr = Long.parseLong(orderEntity.getEndDate().replaceAll("-", "").replaceAll(" ","").replaceAll(":",""));
			long startStr = Long.parseLong(entity.getStartDate().replaceAll("-", "").replaceAll(" ","").replaceAll(":",""));
			if (endStr - startStr >= 0) {
				return returnFailedResult("秘书该时间段已经有约");
			}
		}
		
		//订单号生成 订单编号生成规则： 年月日＋6位随机数。例如：20170101000012）
		entity.setOrderNumber(DateUtil.getNowTimeUnFormat() + Util.get6code());
		
		//计算2个时间的相差时间
		entity.setOrderNumberDays(DateUtil.getDatePoor(DateUtil.stringFormatDateHous(entity.getEndDate()),DateUtil.stringFormatDateHous(entity.getStartDate())));
		
		//计算相差多久
		entity.setTimeDay(DateUtil.getDatePoorDate(DateUtil.stringFormatDateHous(entity.getEndDate()),DateUtil.stringFormatDateHous(entity.getStartDate())));
		
		long state = orderService.addOrder(entity);
		entity.setOrderId(state);
		if (state > 0) {
			SystemMessageEntity messageEntity = new SystemMessageEntity();
			
			UserEntity secretaryEntity = CacheUtil.getUserInfo(entity.getSecretaryUserId());
			UserEntity bossEntity = CacheUtil.getUserInfo(entity.getBossUserId());
			
			messageEntity.setUserId(entity.getSecretaryUserId());
        	messageEntity.setContent("您好，'"+bossEntity.getNickname()+"'向:'"+secretaryEntity.getNickname()+"'发送了聘单，请耐心等待对方处理并合理沟通哦~约定时间前对方未接单默认取消订单。");
        	messageEntity.setSystemType(1);
        	
        	systemMessageService.saveSystemMessage(messageEntity);
			
			return returnSuccessResult(entity);
		}

		return returnFailedResult("订单生成失败");
	}
	
	
	@RequestMapping(value = "/MobileAddOrderBill", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileAddOrderBill(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderBillEntity entity = (OrderBillEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderBillEntity.class);

		long state = orderService.addOrderBill(entity);
		
		if (state > 0) {
			return returnSuccessResult(entity);
		}

		return returnFailedResult("添加订单发票失败");
	}
	
	/**
	 * 订单信息签名
	 */
	@RequestMapping(value = "/MobileAlipayOrderSign", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileAlipayOrderSign(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		
		try {
			String signStr = AlipayUtil.getAlipaySign(p1);
			return returnSuccessResult(signStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return returnFailedResult("获取签名失败");
	}
	
	/**
	 * 支付宝回调接口，处理订单服务端逻辑
	 * /**参数参考：https://doc.open.alipay.com/doc2/detail.htm?treeId=193&articleId=105301&docType=1#s6
		 * total_amount=2.00&
	buyer_id=2088102116773037&
	body=大乐透2.1&
	trade_no=2016071921001003030200089909&
	refund_fee=0.00&
	notify_time=2016-07-19 14:10:49&
	subject=大乐透2.1&
	sign_type=RSA&
	charset=utf-8&
	notify_type=trade_status_sync&
	out_trade_no=0719141034-6418&
	gmt_close=2016-07-19 14:10:46&
	gmt_payment=2016-07-19 14:10:47&
	trade_status=TRADE_SUCCESS&
	version=1.0&
	sign=kPbQIjX+xQc8F0/A6/AocELIjhhZnGbcBN6G4MM/HmfWL4ZiHM6fWl5NQhzXJusaklZ1LFuMo+lHQUELAYeugH8LYFvxnNajOvZhuxNFbN2LhF0l/KL8ANtj8oyPM4NN7Qft2kWJTDJUpQOzCzNnV9hDxh5AaT9FPqRS6ZKxnzM=&
	gmt_create=2016-07-19 14:10:44&
	app_id=2015102700040153&
	seller_id=2088102119685838&
	notify_id=4a91b7a78a503640467525113fb7d8bg8e
		 
	 */
	@RequestMapping(value = "/AlipayNotifyCallBack", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String alipayNotifyCallBack(HttpServletRequest request, HttpServletResponse response) {
		
		
		/**
		 * 实际回调参数
		 * total_amount-------0.01
 buyer_id-------2088702880456819
trade_no-------2017010621001004810238568814
notify_time-------2017-01-06 17:24:48
subject-------聘请订单
sign_type-------RSA
buyer_logon_id-------159****7554
auth_app_id-------2017010404839381
charset-------utf-8
notify_type-------trade_status_sync
invoice_amount-------0.01
out_trade_no-------20170106104466
trade_status-------TRADE_SUCCESS
gmt_payment-------2017-01-06 17:24:48
version-------1.0
point_amount-------0.00
sign-------bpJFvxpdllyujatwHRDOCiMhs1uGh/J0AW7wZ18zA4IQqHJbSYo79SfkezoNeGHC5QsJEnVWq1EN+syXs/tm3Gwyj9eLCPkdI+PitkKe+VgJzLTPkwvcIkpkplVPiOd9/Tk26wWkIvEhr9jdORbTvBJfJJ7AkWbNGgpRxfSZsv0=
gmt_create-------2017-01-06 17:24:47
buyer_pay_amount-------0.01
receipt_amount-------0.01
fund_bill_list-------[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]
app_id-------2017010404839381
seller_id-------2088421458871750
notify_id-------3a1cc0500823ed24710c2eac55a082fm92
seller_email-------530441783@qq.com
		 */
		OrderAlipayCallBackEntity entity = new OrderAlipayCallBackEntity();
		entity.setTotalAmount(Double.valueOf(request.getParameter("total_amount")));
		entity.setBuyerId(request.getParameter("buyer_id"));
//		entity.setBody(request.getParameter("body"));//参数没有
		entity.setTradeNo(request.getParameter("trade_no"));
//		entity.setRefundFee(Double.valueOf(request.getParameter("refund_fee")));
		entity.setNotifyTime(request.getParameter("notify_time"));
		entity.setSubject(request.getParameter("subject"));
		entity.setSignType(request.getParameter("sign_type"));
		entity.setCharset(request.getParameter("charset"));
		entity.setNotifyType(request.getParameter("notify_type"));
		entity.setOutTradeNo(request.getParameter("out_trade_no"));
		entity.setGmtClose(request.getParameter("gmt_close"));
		entity.setGmtPayment(request.getParameter("gmt_payment"));
		entity.setTradeStatus(request.getParameter("trade_status"));
		entity.setVersion(request.getParameter("version"));
		entity.setSign(request.getParameter("sign"));
		entity.setGmtCreate(request.getParameter("gmt_create"));
		entity.setAppId(request.getParameter("app_id"));
		entity.setSellerId(request.getParameter("seller_id"));
		entity.setNotifyId(request.getParameter("notify_id"));
		entity.setReceiptAmount(Double.valueOf(request.getParameter("receipt_amount")));
		/*支付宝逻辑*/
		//1，TODO:参考：https://doc.open.alipay.com/doc2/detail.htm?treeId=193&articleId=105301&docType=1#s6
		
		/*本地逻辑*/
		//1，验证订单号是否存在
		Util.logExceptionINFO("本地订单号为:"+entity.getOutTradeNo()+"===支付宝订单号:"+entity.getTradeNo());
		OrderEntity orderEntity = orderService.getOrderByOrderNumber(entity.getOutTradeNo());
		
		//发短信
		SMSClient.bossSendOrderAndDonePay(orderEntity);
		
		if (orderEntity != null) {
			//说明订单存在,1，验证订单是否已经支付过了
			//2，验证金额是否为订单金额
			//3，seller_id卖家支付宝是否是本平台的
			//4，验证app_id是否是圈城的
			if (orderEntity.getIsPay() == 0) {
				//TODO:为了调试，先注释
				if (orderEntity.getMoney() == entity.getTotalAmount() && 
						AlipayUtil.SELLER_ID.equals(entity.getSellerId()) && 
						AlipayUtil.APP_ID.equals(entity.getAppId())) {
					//TODO:5，判断订单状态 是否是支付成功
					/*数据库逻辑*/
					//如果以上支付宝逻辑和本地逻辑都通过：
					//1，将数据库的订单标记为已支付
					long state = orderService.updateOrderIsPay(orderEntity.getOrderId(), 1);
					if (state > 0) {

						entity.setPayUserId(orderEntity.getBossUserId());
						entity.setPayType(1);
						//订单日志表记录
						orderService.addOrderPayLog(entity);
						
						// 成功返回一个success 的字符串
						return "success";
					}
					
				} else {
					//验证失败，不做处理
					return "fail";
				}
			}
		}

		return "fail";
	}
	
	@RequestMapping(value = "/MobileGetMyOrder", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetMyOrder(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		MyOrderInfo info = (MyOrderInfo) JSONObject.toBean(JSONObject.fromObject(p1), MyOrderInfo.class);

		List<OrderEntity> list = orderService.getAllMyOrder(info, userId);
		
		return returnSuccessResult(list);
	}
	
	@RequestMapping(value = "/MobileModifyOrderState", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileModifyOrderState(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderEntity entity = (OrderEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderEntity.class);

		long state = orderService.updateOrderState(entity.getOrderState(),entity.getOrderId());
		
		if (state > 0) {
			if (entity.getOrderState() == 2) {
				//秘书接单
				OrderEntity orderEntity = orderService.getOrderDetailByOrderId(entity.getOrderId());
				SMSClient.secReceiveOrder(orderEntity);
			}
			return returnSuccessResult("接单成功");
		}

		return returnFailedResult("接单失败,请联系客服");
	}
	
	@RequestMapping(value = "/MobileGetChatBothOrderInfo", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetChatBothOrderInfo(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderEntity entity = (OrderEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderEntity.class);

		entity = orderService.getBothOrderInfo(entity);
		

		return returnSuccessResult(entity);
	}
	
	@RequestMapping(value = "/MobileAddOrderSchedule", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileAddOrderSchedule(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderScheduleEntity entity = (OrderScheduleEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderScheduleEntity.class); 
		
		long state = orderService.addOrderSchedule(entity);
		entity.setOrderId(state);
		if (state > 0) {
			return returnSuccessResult(entity);
		}

		return returnFailedResult("行程添加失败");
	}
	
	@RequestMapping(value = "/MobileGetOrderScheduleByOrderIdAndDate", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetOrderScheduleByOrderIdAndDate(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderScheduleEntity entity = (OrderScheduleEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderScheduleEntity.class); 
		
		List<OrderScheduleEntity> list = orderService.getScheduleByOrderIdAndDate(entity);

		return returnSuccessResult(list);
	}
	
	/**
	 * 取消订单的几种情况
	 * 1，未支付的时候，BOSS可以取消订单
	 * 2，支付了，未开始，8小时前可以取消订单
	 * 3，秘书拒绝接单
	 */
	@RequestMapping(value = "/MobileCancelOrder", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileCancelOrder(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderEntity oldEntity = (OrderEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderEntity.class); 
		
		//根据订单号查询退款金额
		OrderEntity entity = orderService.getOrderDetailByOrderId(oldEntity.getOrderId());
		
		//先判断开始离现在是否小于8小时，如果小于8小时就提示
//		long hour = DateUtil.getDatePoor(DateUtil.stringFormatDateTime(entity.getStartDate()), new Date());
//		if (hour < 8) {
//			return returnFailedResult("8小时内不能取消订单");
//		}
		
		//通知支付宝退款
		try {
			boolean flag = false;
			if (entity.getPayType() == 1) {
				//支付宝
				flag = AlipayUtil.refund(entity.getOrderNumber(), entity.getMoney());
			} else if (entity.getPayType() == 2) {
				//微信
				System.out.println("调用微信退款接口");
				if (StringUtil.isEmpty(entity.getOrderNumber())) {
					return returnFailedResult("订单号不能为空");
				}
				Map<String, String> restmap = WXPayUtil.refundOrder(entity.getOrderNumber(), entity.getMoney());
				
				if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
					flag = true;
				} else {
					flag = false;
				}
			} else if (entity.getPayType() == 3) {
				//银联
				System.out.println("调用银联退款接口");
			}
			if (entity.getIsPay() == 0) {
				//未支付 直接取消订单
				flag = true;
			}
			
			if (flag) {
				long state = orderService.cancelOrder(entity.getOrderId());

				if (state > 0) {
					if (oldEntity.getCancelType() == 1) {
						//1不处理
					} else if (oldEntity.getCancelType() == 2) {
						//2，支付了，未开始，8小时取消订单
						SMSClient.bossCancelOrder(entity);
					} else if (oldEntity.getCancelType() == 3) {
						//3，秘书拒绝接单
						SMSClient.secCancelOrder(entity);
					}
					return returnSuccessResult(entity);
				}
			} else {
				return returnFailedResult("取消订单失败");
			}
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		long state = orderService.cancelOrder(entity.getOrderId());

//		if (state > 0) {
//			return returnSuccessResult(entity);
//		}
//
		return returnFailedResult("取消订单失败");
	}
	
	/**
	 * 订单评价
	 */
	@RequestMapping(value = "/MobileAddOrderComment", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileAddOrderComment(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderCommentEntity entity = (OrderCommentEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderCommentEntity.class);
		//拼接标签内容
		String[] strList = entity.getTag().split(Constants.SPLIT_MARK);
		StringBuilder sBuilder = new StringBuilder();
		for (String string : strList) {
			SkillTagEntity skillTagEntity = CacheUtil.skillTagMap.get(string);
			if (skillTagEntity == null) {
				sBuilder.append(entity.getTag());
				break;
			}else {
				sBuilder.append(skillTagEntity.getTagContent());
			}
			
		}
		entity.setOcContent(sBuilder.toString());
		
		long state = orderService.addOrderComment(entity);

		if (state > 0) {
			//修改这个订单状态为已经评价
			orderService.updateOrderIsComment(entity.getOrderId());
			return returnSuccessResult(entity);
		}

		return returnFailedResult("取消订单失败");
	}
	
	@RequestMapping(value = "/MobileGetOrderComment", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetOrderComment(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderCommentEntity entity = (OrderCommentEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderCommentEntity.class); 
		
		List<OrderCommentEntity> list = orderService.getOrderCommentByOrderId(entity.getOrderId());

		return returnSuccessResult(list);
	}
	
	@RequestMapping(value = "/MobileGetOrderDetailByOrderId", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetOrderDetailByOrderId(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		OrderEntity entity = (OrderEntity) JSONObject.toBean(JSONObject.fromObject(p1), OrderEntity.class); 
		
		entity = orderService.getOrderDetailByOrderId(entity.getOrderId());

		return returnSuccessResult(entity);
	}
	
	
	/**
	 * 微信支付，下订单接口
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/MobileWXPayOrder", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileWXPayOrder(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");

		//参数1 价格
		//参数2 设备类型 (iOS/Android/Web)
		//参数3 订单号
		WXPayEntity entity = (WXPayEntity) JSONObject.toBean(JSONObject.fromObject(p1), WXPayEntity.class);
		Map<String, String> restmap = WXPayUtil.sendOrder(entity, request);
		
		boolean flag = true; // 是否订单创建成功
		
		Map<String, String> payMap = new HashMap<String, String>();
		if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
			payMap.put("appid", WXPayUtil.APP_ID);
			payMap.put("partnerid",  WXPayUtil.MCH_ID);
			payMap.put("prepayid", restmap.get("prepay_id"));
			payMap.put("package", "Sign=WXPay");
			payMap.put("noncestr", restmap.get("nonce_str"));
			payMap.put("timestamp", String.valueOf(System.currentTimeMillis()).toString().substring(0,10));
			try {
				payMap.put("sign", WXPayUtil.getSign(payMap, WXPayUtil.KEY));//需要二次签名，不然客户端会报 支付验证签名失败
			} catch (Exception e) {
				flag = false;
			}
		} else {
			return returnFailedResult(restmap.get("err_code_des"));
		}

		if (flag) {
			//创建成功
			return returnSuccessResult(payMap);
		}

		return returnFailedResult("");
	}
	
	@RequestMapping(value = "/WXpayNotifyCallBack", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public void wxpayNotifyCallBack(HttpServletRequest request, HttpServletResponse response) {
		
		String inputLine;
        StringBuffer notityXml=new StringBuffer();
        try {
            while((inputLine = request.getReader().readLine()) != null) {
                notityXml.append(inputLine);
            }
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Util.logExceptionINFO("接收到的xml："+ notityXml.toString());
        /**
<xml>
  <appid><![CDATA[wx379b943f5f22a6bb]]></appid>
  <bank_type><![CDATA[CFT]]></bank_type>
  <cash_fee><![CDATA[1]]></cash_fee>
  <device_info><![CDATA[iOS]]></device_info>
  <fee_type><![CDATA[CNY]]></fee_type>
  <is_subscribe><![CDATA[N]]></is_subscribe>
  <mch_id><![CDATA[1439824302]]></mch_id>
  <nonce_str><![CDATA[l5CvQMnXw2FEeP5UVGLJvM2gdEzC62yi]]></nonce_str>
  <openid><![CDATA[oCdWGwo6HflI8_lRPeQKHO7QdM1Q]]></openid>
  <out_trade_no><![CDATA[20170224791245]]></out_trade_no>
  <result_code><![CDATA[SUCCESS]]></result_code>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <sign><![CDATA[FC651E44FDD48EC37B40D6755898B2AC]]></sign>
  <time_end><![CDATA[20170224173426]]></time_end>
  <total_fee>1</total_fee>
  <trade_type><![CDATA[APP]]></trade_type>
  <transaction_id><![CDATA[4009922001201702241155104604]]></transaction_id>
</xml>

         */
        try {
        	Map<String,String> map = XmlUtil.xmlParse(notityXml.toString());
            
        	if(map.get("return_code").equalsIgnoreCase("SUCCESS")){
        		OrderWXpayCallBackEntity entity = new OrderWXpayCallBackEntity();
        		entity.setAppId(map.get("appid"));
        		entity.setAttach(map.get("attach"));
        		entity.setBankType(map.get("bank_type")); 
        		entity.setFeeType(map.get("fee_type"));
        		entity.setIsSubscribe(map.get("is_subscribe"));
        		entity.setMchId(map.get("mch_id"));
        		entity.setNonceStr(map.get("nonce_str"));
        		entity.setOpenid(map.get("openid"));
        		entity.setOutTradeNo(map.get("out_trade_no"));
        		entity.setResultCode(map.get("result_code"));
        		entity.setSign(map.get("sign"));
        		entity.setTimeEnd(map.get("time_end"));
        		entity.setTotalFee(Double.valueOf(map.get("total_fee")) / 100);
        		entity.setTradeType(map.get("trade_type"));
        		entity.setTransactionId(map.get("transaction_id"));
        		
        		Util.logExceptionINFO("本地订单号为:"+entity.getOutTradeNo()+"===微信订单号:"+entity.getTransactionId());
        		
        		OrderEntity orderEntity = orderService.getOrderByOrderNumber(entity.getOutTradeNo());
        		
        		//发短信
        		SMSClient.bossSendOrderAndDonePay(orderEntity);
    			
        		if (orderEntity != null) {
        			
        			long state = orderService.updateOrderIsPay(orderEntity.getOrderId(), 2);
        			
        			if (state > 0) {

        				OrderAlipayCallBackEntity logEntity = new OrderAlipayCallBackEntity();
        				logEntity.setPayUserId(orderEntity.getBossUserId());
        				logEntity.setPayType(2);
        				logEntity.setOutTradeNo(entity.getOutTradeNo());
        				logEntity.setTotalAmount(entity.getTotalFee());
        				logEntity.setReceiptAmount(entity.getTotalFee());
        				logEntity.setSign(entity.getSign());
        				String dateStr = DateUtil.stringFormatString(entity.getTimeEnd());
        				logEntity.setGmtPayment(dateStr);
        				logEntity.setSubject(entity.getAttach());
        				logEntity.setTradeStatus(entity.getResultCode());
						orderService.addOrderPayLog(logEntity);
						
						// 成功返回一个success 的字符串
        				String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        		        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        		        out.write(resXml.getBytes());
        		        out.flush();
        		        out.close();
					}
        		}
            }

    		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static void main(String[] args) {
		
		String a = "2017-05-10 16:00";
		String b = "2017-05-10 18:00";
		/*		String c = (DateUtil.getDatePoorDate(DateUtil.stringFormatDateHous(b),DateUtil.stringFormatDateHous(a)));
		System.out.println(c);*/
		
		long s = DateUtil.getDatePoor(DateUtil.stringFormatDateHous(b),DateUtil.stringFormatDateHous(a));
		System.out.println(s);
		/*System.out.println(DateUtil.stringFormatString("20170227150411"));
		
		String str1 = "20170227150411";
		SimpleDateFormat d = new SimpleDateFormat("yyyyMMddHHmmss");
		
		Date date1;
		try {
			date1 = d.parse(str1);
			
			String dString = DateUtil.dateTimeFormatString(date1);
			System.out.println(dString);
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		
	}
}
